<template>
  <div class="app-container">
    <div class="table-container">
      <div class="left">
        <el-form :inline="true" :model="search">
          <el-form-item label="帐户余额">
            <span class="priceAccount">{{userInfo.account | toFixed}}欧元</span>
          </el-form-item>
          <el-form-item label="号码">
            <el-input v-model="search.msisdn" type="text" placeholder="请输入号码"></el-input>
          </el-form-item>
          <el-form-item label="剩余话费">
            <el-input v-model="search.remainingMoney" type="text" placeholder="请输入剩余话费"></el-input>
          </el-form-item>
          <el-form-item label="剩余有效期">
            <el-input v-model="search.nextBillingDateDay" type="text" placeholder="请输入剩余有效期天数"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchSubmit">查询</el-button>
          </el-form-item>
          <!-- <el-form-item>
            <el-button type="success">导出</el-button>
          </el-form-item> -->
        </el-form>
      </div>
    </div>
    <div class="_list">
      <el-table highlight-current-row :data="dataList" style="width: 100%" v-loading="listLoading" :row-class-name="tableRowClassName">
        <el-table-column label="号码" width="180" align="left">
          <template slot-scope="scope">
           <div style="text-align:left;padding-left:10px;">(+{{scope.row.country.dialingPrefix}}) {{scope.row.msisdn}} </div>
           <div style="text-align:left;padding-left:10px;">{{scope.row.country.countryName}}</div>
          </template>
        </el-table-column>
        <el-table-column label="功能">
          <template slot-scope="scope">
            {{scope.row.features.length>1 ?'语音&短信': scope.row.features[0] === 'VOICE'? '语音': '短信' }}
          </template>
        </el-table-column>
        <el-table-column label="类别">
          <template slot-scope="scope">
            {{scope.row.type.indexOf('mobile') > -1 ?'手机': scope.row.type.indexOf('free') > -1 ? '免费电话': '固话' }}
          </template>
        </el-table-column>
        <el-table-column label="月租成本">
          <template slot-scope="scope">
            {{parseFloat(scope.row.cost)}}欧元/月
          </template>
        </el-table-column>
        <el-table-column label="月租价格">
          <template slot-scope="scope">
            {{scope.row.monthPrice || scope.row.country.monthPrice}}欧元/月
          </template>
        </el-table-column>
        <!-- <el-table-column label="通话成本">
          <template slot-scope="scope">
            {{scope.row.callsCost || scope.row.country.inPriceCost}}欧元/分
          </template>
        </el-table-column> -->
         <el-table-column label="通话价格" width="160">
          <template slot-scope="scope">
            <div class="font-12">呼入</div>
            {{scope.row.inPrice || scope.row.country.inPrice}}欧元/分<span class="font-12" style="margin-left:20px;color:red;" @click="callOut(scope.row)">呼出</span>
          </template>
        </el-table-column>
        <el-table-column label="剩余话费" align="center">
          <template slot-scope="scope">
            <span class="price">{{scope.row.remainingMoney | toFixed}}欧元</span>
          </template>
        </el-table-column>
        <el-table-column label="剩余有效期" align="center">
          <template slot-scope="scope">
            <div v-if="!scope.row.oweDay && scope.row.nextBillingDay > 0">{{scope.row.nextBillingDay || 0}}天</div>
            <div v-if="!scope.row.oweDay && scope.row.nextBillingDay > 0">{{scope.row.nextBillingDate | formatDate('YYYY-MM-DD')}}</div>
            <div v-if="scope.row.oweDay">已欠费<span style="color:red;">{{scope.row.oweDay}}</span>天</div>
            <div v-if="scope.row.oweDate">欠费时间:{{scope.row.oweDate | formatDate('YYYY-MM-DD')}}</div>
          </template>
        </el-table-column>
        <el-table-column label="购买时间" width="180" align="center">
          <template slot-scope="scope">
            {{scope.row.createdAt | formatDate}}
          </template>
        </el-table-column>
        <el-table-column label="呼出地址">
          <template slot-scope="scope">
            <el-tooltip class='item' effect='dark' :content="WEB_SERVER_URL + scope.row.appid+'/record'+'?msisdn=' + scope.row.msisdn + '&countryCode='+scope.row.country.countryCode + '&user='+ scope.row.user" placement='top'>
              <a :href="WEB_SERVER_URL + scope.row.appid+'/record'+'?msisdn=' + scope.row.msisdn + '&countryCode='+scope.row.country.countryCode+'&user='+ scope.row.user" target="_blank">{{scope.row.appid}}</a>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <div><el-button type="text" @click="handleTopUp(scope.row)">充值</el-button><el-button type="text" @click="handleUpdatas(scope.row._id)">更新地址</el-button></div>
            <div><el-button type="text" @click="handleCall(scope.row)">呼出设置</el-button><el-button type="text" @click="handleNumberSetup(scope.row)">号码设置</el-button></div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pages">
      <div class="right" v-if="total > 0">
        <el-pagination @current-change="handleCurrentChange" background :current-page.sync="page" layout="total, prev, pager, next" :total="total">
        </el-pagination>
      </div>
    </div>
    <el-dialog title="充值" :visible.sync="dialogVisible" width="390px" top="5vh">
      <el-form ref="dialogForm" :model="form" label-width="110px">
        <el-form-item style="margin-bottom:10px" label="号码">
          <div class="buyNumber"> (+{{rows.dialingPrefix}}) {{rows.msisdn}}</div>
        </el-form-item>
        <el-form-item label="充值话费">
          <el-input v-model="remainingMoney" placeholder="请填写你的充值话费" style="width:200px"></el-input>
        </el-form-item>
        <el-form-item style="margin-top:20px;margin-bottom:30px;">
          <el-button size="medium" type="primary" @click="submitTopUp" :loading="isLoading">{{isBtnLoading?'充值中':'确 定'}}</el-button>
          <div style="height:30px;"></div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="号码设置" :visible.sync="numberSetupdialogVisible" :rules="numberSetupRules" width="380px" top="5vh">
      <el-form ref="numberSetupForm" :model="form" label-width="110px">
         <el-form-item label="号码" style="margin-bottom:10px">
          <div class="buyNumber"> (+{{rows.dialingPrefix}}) {{rows.msisdn}}</div>
          <div class="pos">{{rows.currencyName}}</div>
        </el-form-item>
        <el-form-item style="margin-bottom:10px" label="呼叫转移" prop="callForwarding">
           <el-input v-model="buyInfo.callForwarding" placeholder="填写呼叫转移设置" style="width:200px"></el-input>
        </el-form-item>
        <el-form-item label="月租价格" prop="monthPrice">
          <el-input v-model="buyInfo.monthPrice" placeholder="填写月租价格设置" style="width:200px"></el-input>
        </el-form-item>
         <el-form-item label="呼入价格" prop="inPrice">
          <el-input v-model="buyInfo.inPrice" placeholder="填写呼入价格设置" style="width:200px"></el-input>
        </el-form-item>
        <el-form-item style="margin-top:20px;margin-bottom:30px;">
          <el-button size="medium" type="primary" @click="submitUpdata('numberSetupForm')" :loading="isLoading">{{isBtnLoading?'保存中':'确 定'}}</el-button>
          <div style="height:30px;"></div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog :title="countryName+'呼出价格列表'" :visible.sync="CallListdialogVisible" width="650px" top="5vh">
      <el-form :inline="true" :model="search">
          <el-form-item v-if="callCountryList.length > 0">
            <el-input v-model="countryCode" type="text" placeholder="请输入国家代码"></el-input>
          </el-form-item>
          <el-form-item v-if="callCountryList.length > 0">
            <el-button type="primary" @click="handleCallCurrentChange(1)">查询</el-button>
          </el-form-item>
          <el-form-item v-if="!iScallOut">
            <div class="importExcel">
              <el-button class="btnExcel" type="success">导入</el-button>
              <input type="file" class="fileExcel" ref="fileExcel" @change="importExcel($event.target)" />
            </div>
          </el-form-item>
        </el-form>
      <el-table highlight-current-row :data="callCountryList" style="width: 100%" v-loading="callListLoading">
        <el-table-column label="国家代码">
          <template slot-scope="scope">
            {{scope.row.countryCode}}
          </template>
        </el-table-column>
        <el-table-column label="国家名称">
          <template slot-scope="scope">
            {{scope.row.countryName}}
          </template>
        </el-table-column>
        <el-table-column label="呼出" align="center" width="300">
          <template slot-scope="scope">
            <div class="inPriceCost">
              <span>固话: {{scope.row.telOutPrice}}欧元/分</span>
              <span>手机: {{scope.row.mobileOutPrice}}欧元/分</span>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="操作" v-if="!iScallOut">
          <template slot-scope="scope">
            <div>
               <el-button type="text">编辑</el-button>
              <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          </div>
          </template>
        </el-table-column> -->
      </el-table>
       <div class="pages" v-if="callCountryList.length > 0">
        <div class="right">
          <el-pagination @current-change="handleCallCurrentChange" background :current-page.sync="callPage" layout="total, prev, pager, next" :total="callTotal">
          </el-pagination>
        </div>
      </div>
      <div style="height:20px;"></div>
    </el-dialog>
  </div>
</template>
<script>
import mixinsTable from '@/utils/mixins.table';
import { mapGetters } from 'vuex';
export default {
  name: 'clientlist',
  mixins: [mixinsTable],
  data() {
    return {
      WEB_SERVER_URL: process.env.VUE_APP_WEB_SERVER_URL,
      isLoading: false,
      iScallOut: false,
      numberSetupdialogVisible: false,
      isBtnLoading: false,
      search: {},
      numberId: '',
      countryCode: '',
      callCountryList: [],
      countryName: '',
      buyInfoId: '',
      CallListdialogVisible: false,
      account: '',
      servicePath: '/nexmo/client',
      callListLoading: false,
      callTotal: 0,
      callPage: 1,
      money: null,
      remainingMoney: null,
      rows: {
        dialingPrefix: '',
        msisdn: '',
        currencyName: ''
      },
      form: {},
      numberSetupRules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }]
      },
      buyInfo: {
      }
    };
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  created() {
    this.getClientList({});
  },
  methods: {
    tableRowClassName(row, rowIndex) {
      if (row.owe) {
        return 'warning-row';
      }
    },
    handleUpdatas(id) {
      this.listLoading = true;
      this.moduleService['update']({ _id: id, appid: 'update' }).then(res => {
        this.listLoading = false;
        this.$message.success('更新成功');
        this.getClientList(this.search);
      });
    },
    goWebUrl(url, msisdn, user) {
      location.href = url + '?msisdn=' + msisdn + '&user=' + user;
    },
    searchSubmit() {
      this.search.page = 1;
      this.getClientList(this.search);
    },
    submitTopUp(formName) {
      this.isBtnLoading = true;
      this.listLoading = true;
      var _remainingMoney = this.money + parseFloat(this.remainingMoney);
      // var _remainingMoney = this.money > 0 ? parseFloat(this.money) + parseFloat(this.remainingMoney) : parseFloat(this.remainingMoney);
      var options = {
        _id: this.buyInfoId,
        money: parseFloat(this.remainingMoney),
        remainingMoney: _remainingMoney,
        dialingPrefix: this.rows.dialingPrefix,
        msisdn: this.rows.msisdn,
        countryName: this.rows.currencyName
      };

      this.moduleService['update'](options).then(res => {
        this.listLoading = false;
        this.isBtnLoading = false;
        this.dialogVisible = false;
        this.$message.success('充值成功');
        this.getClientList(this.search);
      });
    },
    submitUpdata(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.listLoading = true;
          this.moduleService['update'](this.buyInfo).then(res => {
            this.listLoading = false;
            this.numberSetupdialogVisible = false;
            this.$message.success('更新成功');
            this.getClientList(this.search);
          });
        } else {
          return false;
        }
      });
    },
    importExcel(obj) {
      if (!this.numberId) {
        this.$message.warning('没有获取到号码');
        return;
      }
      let file = obj.files[0];
      let types = file.name.split('.')[1];
      let fileType = ['xlsx', 'xlc', 'xlm', 'xls', 'xlt', 'xlw', 'csv'].some(item => item === types);
      if (!fileType) {
        this.$message.warning('格式错误！请重新选择');
        return;
      }
      this.callListLoading = true;
      var files = new FormData();
      files.append('file', file);
      files.append('price', 'priceout');
      files.append('msisdn', this.rows.msisdn);
      files.append('_id', this.numberId);
      this.$API.importExcel(files).then((data) => {
        if (data.code === 200) {
          this.getCallCountryList({ page: 1 });
          this.callListLoading = false;
          this.$message.success('导入成功!');
        }
        this.$refs.fileExcel.value = '';
      }).catch((err) => {
        if (err) {
          this.callListLoading = false;
          this.$refs.fileExcel.value = '';
        }
      });
    },
    handleCallCurrentChange(val) {
      this.getCallCountryList({ page: val, countryCode: this.countryCode || null, msisdn: this.numberId });
    },
    getCallCountryList(query) {
      this.callListLoading = true;
      this.$API.callOutList(query).then((res) => {
        this.callCountryList = res.data.result;
        this.callTotal = res.data.total;
        this.callListLoading = false;
      }).catch((err) => {
        if (err) {
          this.callListLoading = false;
        }
      });
    },
    callOut(row) {
      this.servicePath = '/nexmo/priceout';
      this.countryName = row.country.countryName;
      this.CallListdialogVisible = true;
      this.rows.msisdn = row.msisdn;
      this.getCallCountryList({ page: 1, msisdn: row.msisdn });
      this.iScallOut = true;
    },
    handleCall(row) {
      this.numberId = row.msisdn;
      this.iScallOut = false;
      this.countryName = row.country.countryName;
      this.getCallCountryList({ page: 1, msisdn: row.msisdn });
      this.CallListdialogVisible = true;
    },
    getClientList(query) {
      this.listLoading = true;
      this.$API.clientList(query).then((res) => {
        this.dataList = res.data.result;
        this.total = res.data.total;
        this.account = res.data.account;
        this.listLoading = false;
      }).catch((err) => {
        if (err) {
          this.listLoading = false;
        }
      });
    },
    handleCurrentChange(val) {
      this.search.page = val;
      this.getClientList(this.search);
    },
    // 充值功能
    handleTopUp(row) {
      this.money = row.remainingMoney;
      this.remainingMoney = null;
      this.rows.dialingPrefix = row.country.dialingPrefix;
      this.rows.msisdn = row.msisdn;
      this.rows.currencyName = row.country.countryName;
      this.servicePath = '/nexmo/client';
      this.buyInfoId = row._id;
      this.dialogVisible = true;
    },
    handleNumberSetup(row) {
      this.dialogState = 'update';
      this.rows.dialingPrefix = row.country.dialingPrefix;
      this.rows.msisdn = row.msisdn;
      this.rows.currencyName = row.country.countryName;
      this.buyInfo = {
        _id: row._id,
        monthPrice: row.monthPrice,
        inPrice: row.inPrice,
        callForwarding: row.callForwarding
      };
      this.numberSetupdialogVisible = true;
    }
  }
};
</script>
<style lang="scss">
.priceAccount,.price{
  color:red;
  margin-right: 50px;
}
.el-table .warning-row {
    background: #f36464;
  }

.priceAccount{
  font-size:14px;
}
.price,.font-12{
  font-size:12px;
}
.price{
   text-align: center;
   display: block;
   width:100%;
}
.importExcel{
  position: relative;
  .btnExcel{
    position: absolute;
    left:0;
    right: 0;
  }
  .fileExcel{
    opacity: 0;
    width:56px;
    height: 32px;
    z-index: 999;
    vertical-align: top;
    cursor: pointer;
  }
}
.inPriceCost{
  display: flex;
  span{
    flex: 1;
    display: block;
  }
}
</style>
